# -*- coding: utf-8 -*-
# created on 2016/03/30
from sympy import Union
from mathsolver.functions.base import BaseFunction, BaseValue, BaseNumber, BaseSymbolValue, new_latex
from mathsolver.functions.daoshu.jizhi import HanShuJiZhi
from mathsolver.functions.hanshu.helper import check_func


class JiZhiDianGeShu(BaseFunction):
    """求函数极值点个数"""
    canshu = None

    def solver(self, *args):
        # 计算函数极值点
        jizhi_solver = HanShuJiZhi(self.known).solver(*args)
        self.steps.extend(jizhi_solver.steps)
        jizhidian = jizhi_solver.jizhidian

        # 不含参数：[[jizhi_x, jizhi_y], ...]
        if isinstance(jizhidian, list):
            jizhi_n = len(jizhidian)
            self.steps.append(["", "所以函数极值点个数为 %s" % jizhi_n])
        # 含参数：{canshu_range: [[jizhi_x, jizhi_y], [*], ...], ... }
        else:
            canshu = jizhi_solver.canshu
            self.canshu = canshu
            jizhi_n = {_range: len(_jizhi) for _range, _jizhi in jizhidian.items()}
            # 考虑极值点不存在的情况
            if jizhi_solver.zero_jizhi_interval:
                jizhi_n.update({jizhi_solver.zero_jizhi_interval: 0})

            buzou = ", ".join(["当 %s ∈ %s 时，函数有%s个极值点" % (new_latex(canshu), new_latex(_range), _n)
                                for _range, _n in jizhi_n.items()])
            self.steps.append(["", "所以，" + buzou])

        self.output.append(BaseValue(jizhi_n))
        self.label.add("求函数极值点个数")
        return self


class JiZhiDianGeShuQiuCan(BaseFunction):
    """已知函数极值点个数求参数
    
    输入 
        args[0] BaseFunc, BaseEq
        args[1] BaseNumber, "有","没有" """

    def solver(self, *args):
        func = check_func(args[0])

        # 求函数极值点个数
        geshu_solver = JiZhiDianGeShu(self.known).solver(func)
        reverse_result = geshu_solver.output[0].value
        self.steps.extend(geshu_solver.steps)

        result = {v: k for k, v in reverse_result.items()}
        if isinstance(args[1], BaseNumber):
            output_result = result[args[1].sympify()]
        elif "没有" in args[1]:
            output_result = result[0]
        else:  # 有
            output_result = Union(*[_range for _n, _range in result.items() if _n != 0])

        self.output.append(BaseSymbolValue({geshu_solver.canshu: output_result}))
        self.steps.append(["", "所以 %s ∈ %s" % (new_latex(geshu_solver.canshu), new_latex(output_result))])
        self.label.add("已知函数极值点个数求参数")
        return self


if __name__ == '__main__':
    pass
